from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from app01 import models
from app01.utils.form import AdminModelForm, AdminResetModelForm, AdminEditModelForm, AdminLevelModelForm
from app01.utils.pagination import Pagination


def admin_list(request):
    """ 管理员列表 """
    if request.session.get("info")["level"] == 3 or request.session.get("info")["level"] == 2:
        return render(request, 'error.html')
    # info_dict = request.session["info"]
    # print(info_dict["id"])
    # print(info_dict['name'])

    # 构造搜索
    data_dict = {}
    search_data = request.GET.get('q', "")
    if search_data:
        data_dict["username__contains"] = search_data

    # 根据搜索条件去数据库获取
    queryset = models.Admin.objects.filter(**data_dict)
    # 分页
    page_object = Pagination(request, queryset)
    context = {
        'queryset': page_object.page_queryset,
        'page_string': page_object.html(),
        "search_data": search_data
    }
    return render(request, 'admin_list.html', context)


def admin_add(request):
    """ 添加管理员 """
    if request.session.get("info")["level"] == 3 or request.session.get("info")["level"] == 2:
        return render(request, 'error.html')
    title = "新建管理员"
    if request.method == "GET":
        form = AdminModelForm()
        return render(request, 'admin_change.html', {'form': form, "title": title})
    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')

    return render(request, 'admin_change.html', {'form': form, "title": title})


def admin_delete(request):
    """ 删除管理员 """
    if request.session.get("info")["level"] == 3 or request.session.get("info")["level"] == 2:
        return render(request, 'error.html')
    # 获取ajax发送的ID http://127.0.0.1:8000/user/delete/?nid=1
    uid = request.GET.get('uid')

    # 删除前确认数据是否存在
    exists = models.Admin.objects.filter(id=uid).exists()
    if not exists:
        # 如果数据不存在返回错误信息
        return JsonResponse({"status": False, 'error': "删除失败，数据不存在。"})
    # 如果存在进行删除操作
    models.Admin.objects.filter(id=uid).delete()
    return JsonResponse({"status": True})


def admin_edit(request, nid):
    """ 编辑管理员 """
    if request.session.get("info")["level"] == 3 or request.session.get("info")["level"] == 2:
        return render(request, 'error.html')

    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        # return render(request, 'error.html', {"msg": "数据不存在"})
        return redirect('/admin/list/')

    title = "编辑管理员"
    if request.method == "GET":
        form = AdminEditModelForm(instance=row_object)
        return render(request, 'admin_change.html', {"form": form, "title": title})

    form = AdminEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, 'admin_change.html', {"form": form, "title": title})


def admin_reset(request, nid):
    """ 重置密码 """
    if request.session.get("info")["level"] == 3 or request.session.get("info")["level"] == 2:
        return render(request, 'error.html')

    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        return redirect('/admin/list/')

    title = "重置密码 —— {}".format(row_object.username)

    if request.method == "GET":
        form = AdminResetModelForm()
        return render(request, 'admin_change.html', {"form": form, "title": title})

    form = AdminResetModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, 'admin_change.html', {"form": form, "title": title})


def admin_level(request, nid):
    """ 更改等级 """
    if request.session.get("info")["level"] == 3 or request.session.get("info")["level"] == 2:
        return render(request, 'error.html')

    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        return redirect('/admin/list/')

    title = "更改等级 —— {}".format(row_object.username)

    if request.method == "GET":
        form = AdminLevelModelForm()
        return render(request, 'admin_change.html', {"form": form, "title": title})

    form = AdminLevelModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, 'admin_change.html', {"form": form, "title": title})


@csrf_exempt
def info_list(request):
    if request.method == "GET":
        return render(request, 'info_list_admin.html')

    admin_info = request.session.get('info')
    level = admin_info["level"]
    power = []
    if level == 1:
        power = ["是", "是", "是", "是", ]
    elif level == 2:
        power = ["否", "是", "是", "是", ]
    else:
        power = ["否", "否", "否", "是", ]

    data = {
        "power_admin": power[0],
        "power_user": power[1],
        "power_depart": power[2],
        "power_record": power[3],
    }
    result = {
        "status": True,
        "data": data
    }
    return JsonResponse(result)
